package com.rzfk.app.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.rzfk.app.domain.AppBook;
import com.rzfk.app.domain.AppBookCategory;
import com.rzfk.app.domain.AppBookContent;
import com.rzfk.app.domain.AppInteractRecord;
import com.rzfk.app.service.IAppBookService;
import com.rzfk.app.service.IAppInteractRecordService;
import com.rzfk.common.core.page.TableDataInfo;
import com.rzfk.common.utils.IDUtils;
import com.rzfk.common.utils.PageUtils;
import com.rzfk.common.utils.SecurityUtils;
import com.rzfk.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.rzfk.common.annotation.RepeatSubmit;
import com.rzfk.common.annotation.Log;
import com.rzfk.common.core.controller.BaseController;
import com.rzfk.common.core.domain.R;
import com.rzfk.common.core.validate.AddGroup;
import com.rzfk.common.core.validate.EditGroup;
import com.rzfk.common.core.validate.QueryGroup;
import com.rzfk.common.enums.BusinessType;
import com.rzfk.common.utils.poi.ExcelUtil;
import com.rzfk.app.domain.vo.AppBookContentVo;
import com.rzfk.app.domain.bo.AppBookContentBo;
import com.rzfk.app.service.IAppBookContentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiOperation;

/**
 * 书籍内容Controller
 *
 * @author streaker
 * @date 2023-02-03
 */
@Validated
@Api(value = "书籍内容控制器", tags = {"书籍内容管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/app/bookContent")
public class AppBookContentController extends BaseController {

    private final IAppBookContentService iAppBookContentService;

    private final IAppBookService iAppBookService;

    private final IAppInteractRecordService iAppInteractRecordService;

    @GetMapping("/addContent")
    public void addContent() throws Exception {
        List<AppBook> books = iAppBookService.list();
        for (int x = 3547; x < books.size(); x++) {
            System.out.println("*****************************" + x + "  " + books.get(x).getName());
            String url = "https://www.bookstack.cn" + books.get(x).getReadHref();
            url = URLDecoder.decode(url, String.valueOf(StandardCharsets.UTF_8));
            //模拟浏览器访问，防止阻止跳到登录页面
            Connection mozilla = Jsoup.connect(url).userAgent("Mozilla");
            Document document = mozilla.get();
            Element element = document.body();
            Element menus = element.getElementsByClass("article-menu").get(0);
            Elements menu = menus.getElementsByTag("ul").get(0).children();
            for (int i = 0; i < menu.size(); i++) {
                Element one = menu.get(i);
                String href1 = one.getElementsByTag("a").eq(0).attr("href");
                String name1 = one.getElementsByTag("a").eq(0).text();
                System.out.println("----1-----name: " + name1 + "   -----1----href: " + href1);
                Elements twos = one.getElementsByTag("ul");
                AppBookContent appBookContent1 = saveContent(books.get(x).getId(), name1, String.valueOf(i + 1), href1, Long.parseLong("0"), "1");
                if (!twos.isEmpty()) {
                    for (int j = 0; j < twos.get(0).children().size(); j++) {
                        Element two = twos.get(0).children().get(j);
                        String href2 = two.getElementsByTag("a").eq(0).attr("href");
                        String name2 = two.getElementsByTag("a").eq(0).text();
                        System.out.println(">>>> >>>> ------2-----name: " + name2 + "   -----2----href: " + href2);
                        AppBookContent appBookContent2 = saveContent(books.get(x).getId(), name2, (i + 1) + "-" + (j + 1), href2, appBookContent1.getId(), "2");
                        Elements threes = two.getElementsByTag("ul");
                        if (!threes.isEmpty()) {
                            for (int k = 0; k < threes.get(0).children().size(); k++) {
                                Element three = threes.get(0).children().get(k);
                                String href3 = three.getElementsByTag("a").eq(0).attr("href");
                                String name3 = three.getElementsByTag("a").eq(0).text();
                                AppBookContent appBookContent3 = saveContent(books.get(x).getId(), name3, (i + 1) + "-" + (j + 1) + "-" + (k + 1), href3, appBookContent2.getId(), "3");
                                System.out.println(">>>> >>>> >>>> ------3-----name: " + name3 + "   -----3----href: " + href3);
                                Elements fours = three.getElementsByTag("ul");
                                if (!fours.isEmpty()) {
                                    for (int l = 0; l < fours.get(0).children().size(); l++) {
                                        Element four = fours.get(0).children().get(l);
                                        String href4 = four.getElementsByTag("a").eq(0).attr("href");
                                        String name4 = four.getElementsByTag("a").eq(0).text();
                                        AppBookContent appBookContent4 = saveContent(books.get(x).getId(), name4, (i + 1) + "-" + (j + 1) + "-" + (k + 1) + "-" + (l + 1), href4, appBookContent3.getId(), "4");
                                        System.out.println(">>>> >>>> >>>> >>>> ------4-----name: " + name4 + "   -----4----href: " + href4);
                                        Elements fives = four.getElementsByTag("ul");
                                        if (!fives.isEmpty()) {
                                            for (int m = 0; m < fives.get(0).children().size(); m++) {
                                                Element five = fives.get(0).children().get(m);
                                                String href5 = five.getElementsByTag("a").eq(0).attr("href");
                                                String name5 = five.getElementsByTag("a").eq(0).text();
                                                AppBookContent appBookContent5 = saveContent(books.get(x).getId(), name5, (i + 1) + "-" + (j + 1) + "-" + (k + 1) + "-" + (l + 1) + "-" + (m + 1), href5, appBookContent4.getId(), "5");
                                                System.out.println(">>>> >>>> >>>> >>>> >>>> ------5-----name: " + name5 + "   -----5----href: " + href5);
                                                Elements sixs = five.getElementsByTag("ul");
                                                if (!sixs.isEmpty()) {
                                                    for (int n = 0; n < sixs.get(0).children().size(); n++) {
                                                        Element six = sixs.get(0).children().get(n);
                                                        String href6 = six.getElementsByTag("a").eq(0).attr("href");
                                                        String name6 = six.getElementsByTag("a").eq(0).text();
                                                        AppBookContent appBookContent6 = saveContent(books.get(x).getId(), name6, (i + 1) + "-" + (j + 1) + "-" + (k + 1) + "-" + (l + 1) + "-" + (m + 1) + "-" + (n + 1), href6, appBookContent5.getId(), "6");
                                                        System.out.println(">>>> >>>> >>>> >>>> >>>> >>>> ------6-----name: " + name6 + "   -----6----href: " + href6);
                                                        Elements sevens = six.getElementsByTag("ul");
                                                        if (!sevens.isEmpty()) {
                                                            for (int o = 0; o < sevens.get(0).children().size(); o++) {
                                                                Element seven = sevens.get(0).children().get(o);
                                                                String href7 = seven.getElementsByTag("a").eq(0).attr("href");
                                                                String name7 = seven.getElementsByTag("a").eq(0).text();
                                                                AppBookContent appBookContent7 = saveContent(books.get(x).getId(), name7, (i + 1) + "-" + (j + 1) + "-" + (k + 1) + "-" + (l + 1) + "-" + (m + 1) + "-" + (n + 1) + "-" + (o + 1), href7, appBookContent6.getId(), "7");
                                                                System.out.println(">>>> >>>> >>>> >>>> >>>> >>>> >>>> ------7-----name: " + name7 + "   -----7----href: " + href7);
                                                                Elements eights = seven.getElementsByTag("ul");
                                                                if (!eights.isEmpty()) {
                                                                    for (int p = 0; p < eights.get(0).children().size(); p++) {
                                                                        Element eight = eights.get(0).children().get(p);
                                                                        String href8 = eight.getElementsByTag("a").eq(0).attr("href");
                                                                        String name8 = eight.getElementsByTag("a").eq(0).text();
                                                                        AppBookContent appBookContent8 = saveContent(books.get(x).getId(), name8, (i + 1) + "-" + (j + 1) + "-" + (k + 1) + "-" + (l + 1) + "-" + (m + 1) + "-" + (n + 1) + "-" + (o + 1) + "-" + (p + 1), href8, appBookContent7.getId(), "8");
                                                                        System.out.println(">>>> >>>> >>>> >>>> >>>> >>>> >>>> >>>> ------8-----name: " + name8 + "   -----8----href: " + href8);
                                                                        Elements nines = eight.getElementsByTag("ul");
                                                                        if (!nines.isEmpty()) {
                                                                            for (int q = 0; q < nines.get(0).children().size(); q++) {
                                                                                Element nine = nines.get(0).children().get(q);
                                                                                String href9 = nine.getElementsByTag("a").eq(0).attr("href");
                                                                                String name9 = nine.getElementsByTag("a").eq(0).text();
                                                                                AppBookContent appBookContent9 = saveContent(books.get(x).getId(), name9, (i + 1) + "-" + (j + 1) + "-" + (k + 1) + "-" + (l + 1) + "-" + (m + 1) + "-" + (n + 1) + "-" + (o + 1) + "-" + (p + 1) + "-" + (q + 1), href9, appBookContent8.getId(), "9");
                                                                                System.out.println(">>>> >>>> >>>> >>>> >>>> >>>> >>>> >>>> >>>> ------9-----name: " + name9 + "   -----9----href: " + href9);
                                                                            }
                                                                        }
                                                                    }
                                                                }

                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @GetMapping("/addContent1")
    public void addContent1() throws Exception {
        QueryWrapper<AppBookContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("content");
        queryWrapper.last("limit 10000");
        List<AppBookContent> books = iAppBookContentService.list(queryWrapper);
        //多线程
        List<List<AppBookContent>> lists = splitList(books, 1000);
        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        for (List<AppBookContent> listSub : lists) {
            try {
                //异步线程要做的事情
                for (AppBookContent t : listSub
                ) {
                    String url = "https://www.bookstack.cn" + t.getHref();
                    System.out.println("**********************1 " + url);
                    url = URLDecoder.decode(url, String.valueOf(StandardCharsets.UTF_8));
//            //模拟浏览器访问，防止阻止跳到登录页面
//            Connection mozilla = Jsoup.connect(url).userAgent("Mozilla");
//            Document document = mozilla.get();
                    // 获取文档对象
                    Document document = null;
                    try {
                        Connection con = Jsoup.connect(url).userAgent(
                                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
                                .timeout(30000); // 设置连接超时时间

                        Connection.Response response = con.execute();

                        if (response.statusCode() == 200) {
                            document = con.get();
                            Element element = document.body();
                            Element j_goodsList = element.getElementsByTag("article").get(0);
                            System.out.println(j_goodsList.toString());
                            t.setContent(j_goodsList.toString());
                            iAppBookContentService.updateById(t);
                        } else {
                            System.out.println(response.statusCode());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println(e.toString());
                    }
                }
            } catch (Exception e) {
                System.out.println("阻塞异常:" + e.getMessage());
            } finally {
                countDownLatch.countDown();// 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
            }
        }
        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成，才会走下面的；
            // 这样就可以在下面拿到所有线程执行完的集合结果
        } catch (Exception e) {
            System.out.println("阻塞异常:" + e.getMessage());
        }

    }

    @GetMapping("/addContent2")
    public void addContent2() throws Exception {
        QueryWrapper<AppBookContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("content");
        queryWrapper.last("limit 10000");
        queryWrapper.orderByDesc("id");
        List<AppBookContent> books = iAppBookContentService.list(queryWrapper);
        //多线程
        List<List<AppBookContent>> lists = splitList(books, 1000);
        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        for (List<AppBookContent> listSub : lists) {
            try {
                //异步线程要做的事情
                for (AppBookContent t : listSub
                ) {
                    String url = "https://www.bookstack.cn" + t.getHref();
                    System.out.println("**********************2 " + url);
                    url = URLDecoder.decode(url, String.valueOf(StandardCharsets.UTF_8));
//            //模拟浏览器访问，防止阻止跳到登录页面
//            Connection mozilla = Jsoup.connect(url).userAgent("Mozilla");
//            Document document = mozilla.get();
                    // 获取文档对象
                    Document document = null;
                    try {
                        Connection con = Jsoup.connect(url).userAgent(
                                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
                                .timeout(30000); // 设置连接超时时间

                        Connection.Response response = con.execute();

                        if (response.statusCode() == 200) {
                            document = con.get();
                            Element element = document.body();
                            Element j_goodsList = element.getElementsByTag("article").get(0);
                            System.out.println(j_goodsList.toString());
                            t.setContent(j_goodsList.toString());
                            iAppBookContentService.updateById(t);
                        } else {
                            System.out.println(response.statusCode());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println(e.toString());
                    }
                }
            } catch (Exception e) {
                System.out.println("阻塞异常:" + e.getMessage());
            } finally {
                countDownLatch.countDown();// 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
            }
        }
        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成，才会走下面的；
            // 这样就可以在下面拿到所有线程执行完的集合结果
        } catch (Exception e) {
            System.out.println("阻塞异常:" + e.getMessage());
        }

    }

    @GetMapping("/addContent3")
    public void addContent3() throws Exception {
        QueryWrapper<AppBookContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("content");
        queryWrapper.last("limit 10000");
        queryWrapper.orderByDesc("seq");
        List<AppBookContent> books = iAppBookContentService.list(queryWrapper);
        //多线程
        List<List<AppBookContent>> lists = splitList(books, 1000);
        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        for (List<AppBookContent> listSub : lists) {
            try {
                //异步线程要做的事情
                for (AppBookContent t : listSub
                ) {
                    String url = "https://www.bookstack.cn" + t.getHref();
                    System.out.println("**********************3 " + url);
                    url = URLDecoder.decode(url, String.valueOf(StandardCharsets.UTF_8));
//            //模拟浏览器访问，防止阻止跳到登录页面
//            Connection mozilla = Jsoup.connect(url).userAgent("Mozilla");
//            Document document = mozilla.get();
                    // 获取文档对象
                    Document document = null;
                    try {
                        Connection con = Jsoup.connect(url).userAgent(
                                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
                                .timeout(30000); // 设置连接超时时间

                        Connection.Response response = con.execute();

                        if (response.statusCode() == 200) {
                            document = con.get();
                            Element element = document.body();
                            Element j_goodsList = element.getElementsByTag("article").get(0);
                            System.out.println(j_goodsList.toString());
                            t.setContent(j_goodsList.toString());
                            iAppBookContentService.updateById(t);
                        } else {
                            System.out.println(response.statusCode());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println(e.toString());
                    }
                }
            } catch (Exception e) {
                System.out.println("阻塞异常:" + e.getMessage());
            } finally {
                countDownLatch.countDown();// 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
            }
        }
        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成，才会走下面的；
            // 这样就可以在下面拿到所有线程执行完的集合结果
        } catch (Exception e) {
            System.out.println("阻塞异常:" + e.getMessage());
        }

    }


    @GetMapping("/addContent4")
    public void addContent4() throws Exception {
        QueryWrapper<AppBookContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("content");
        queryWrapper.last("limit 10000");
        queryWrapper.orderByDesc("level");
        List<AppBookContent> books = iAppBookContentService.list(queryWrapper);
        //多线程
        List<List<AppBookContent>> lists = splitList(books, 1000);
        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        for (List<AppBookContent> listSub : lists) {
            try {
                //异步线程要做的事情
                for (AppBookContent t : listSub
                ) {
                    String url = "https://www.bookstack.cn" + t.getHref();
                    System.out.println("**********************4 " + url);
                    url = URLDecoder.decode(url, String.valueOf(StandardCharsets.UTF_8));
//            //模拟浏览器访问，防止阻止跳到登录页面
//            Connection mozilla = Jsoup.connect(url).userAgent("Mozilla");
//            Document document = mozilla.get();
                    // 获取文档对象
                    Document document = null;
                    try {
                        Connection con = Jsoup.connect(url).userAgent(
                                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
                                .timeout(30000); // 设置连接超时时间

                        Connection.Response response = con.execute();

                        if (response.statusCode() == 200) {
                            document = con.get();
                            Element element = document.body();
                            Element j_goodsList = element.getElementsByTag("article").get(0);
                            System.out.println(j_goodsList.toString());
                            t.setContent(j_goodsList.toString());
                            iAppBookContentService.updateById(t);
                        } else {
                            System.out.println(response.statusCode());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println(e.toString());
                    }
                }
            } catch (Exception e) {
                System.out.println("阻塞异常:" + e.getMessage());
            } finally {
                countDownLatch.countDown();// 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
            }
        }
        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成，才会走下面的；
            // 这样就可以在下面拿到所有线程执行完的集合结果
        } catch (Exception e) {
            System.out.println("阻塞异常:" + e.getMessage());
        }

    }

    @GetMapping("/addContent5")
    public void addContent5() throws Exception {
        QueryWrapper<AppBookContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("content");
        queryWrapper.last("limit 50000");
        List<AppBookContent> books = iAppBookContentService.list(queryWrapper);
        for (int i = 0; i < books.size(); i++) {
            String url = "https://www.bookstack.cn" + books.get(i).getHref();
            System.out.println("**********************1 " + url);
            url = URLDecoder.decode(url, String.valueOf(StandardCharsets.UTF_8));
            //模拟浏览器访问，防止阻止跳到登录页面
            Connection mozilla = Jsoup.connect(url).userAgent("Mozilla");
//            Document document = mozilla.get();
//            Element element = document.body();
            Document document = null;
            try {
                Connection con = Jsoup.connect(url).userAgent(
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
                        .timeout(30000); // 设置连接超时时间

                Connection.Response response = con.execute();

                if (response.statusCode() == 200) {
                    document = con.get();
                    Element element = document.body();
                    Element j_goodsList = element.getElementsByTag("article").get(0);
                    System.out.println(j_goodsList.toString());
                    books.get(i).setContent(j_goodsList.toString());
                    iAppBookContentService.updateById(books.get(i));
                } else {
                    System.out.println(response.statusCode());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.toString());
            }
        }

    }

    @GetMapping("/addContent6")
    public void addContent6() throws Exception {
        QueryWrapper<AppBookContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("content");
        queryWrapper.last("limit 50000");
        queryWrapper.orderByDesc("id");
        List<AppBookContent> books = iAppBookContentService.list(queryWrapper);
        for (int i = 0; i < books.size(); i++) {
            String url = "https://www.bookstack.cn" + books.get(i).getHref();
            System.out.println("**********************2 " + url);
            url = URLDecoder.decode(url, String.valueOf(StandardCharsets.UTF_8));
//            //模拟浏览器访问，防止阻止跳到登录页面
//            Connection mozilla = Jsoup.connect(url).userAgent("Mozilla");
//            Document document = mozilla.get();
            // 获取文档对象
            Document document = null;
            try {
                Connection con = Jsoup.connect(url).userAgent(
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
                        .timeout(30000); // 设置连接超时时间

                Connection.Response response = con.execute();

                if (response.statusCode() == 200) {
                    document = con.get();
                    Element element = document.body();
                    Element j_goodsList = element.getElementsByTag("article").get(0);
                    System.out.println(j_goodsList.toString());
                    books.get(i).setContent(j_goodsList.toString());
                    iAppBookContentService.updateById(books.get(i));
                } else {
                    System.out.println(response.statusCode());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.toString());
            }

        }

    }

    /**
     * @param list
     * @param len
     * @return
     */
    public static <T> List<List<T>> splitList(List<T> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return null;
        }

        List<List<T>> result = new ArrayList<List<T>>();


        int size = list.size();
        int count = (size + len - 1) / len;


        for (int i = 0; i < count; i++) {
            List<T> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
            result.add(subList);
        }
        return result;
    }

    public AppBookContent saveContent(Long bookId, String catalogueName, String seq, String href, Long parentId, String level) {
        AppBookContent appBookContent = new AppBookContent();
        appBookContent.setId(IDUtils.getId());
        appBookContent.setBookId(bookId);
        appBookContent.setCatalogueName(catalogueName);
        appBookContent.setSeq(seq);
        appBookContent.setHref(href);
        appBookContent.setLevel(level);
        appBookContent.setParentId(parentId);
        iAppBookContentService.save(appBookContent);
        return appBookContent;
    }

    /**
     * 查询书籍内容列表
     */
    @ApiOperation("查询书籍内容列表")
    @PreAuthorize("@ss.hasPermi('app:bookContent:list')")
    @GetMapping("/list")
    public R<List<AppBookContentVo>> list(@Validated(QueryGroup.class) AppBookContentBo bo) {
        List<AppBookContentVo> list = iAppBookContentService.queryList(bo);
        return R.success(list);
    }

    /**
     * 查询书籍内容列表
     */
    @ApiOperation("查询书籍内容列表")
    @GetMapping("/chaptersList")
    public TableDataInfo<AppBookContent> chaptersList(@Validated(QueryGroup.class) AppBookContentBo bo) {
        QueryWrapper<AppBookContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id,catalogue_name,seq,level,parent_id ");
        queryWrapper.eq("book_id", bo.getBookId());
        queryWrapper.last("limit 1000");
        List<AppBookContent> list = iAppBookContentService.list(queryWrapper);
        return PageUtils.buildDataInfo(list);
    }

    /**
     * 查询书籍内容
     */
    @ApiOperation("查询书籍内容列表")
    @GetMapping("/chaptersContent")
    public TableDataInfo<AppBookContent> chaptersContent(@RequestParam Map<String, Object> params) throws Exception {
        QueryWrapper<AppBookContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id,catalogue_name,seq,level,parent_id ");
        queryWrapper.eq("book_id", params.get("bookId").toString());
        queryWrapper.last("limit 1000");
        List<AppBookContent> list = iAppBookContentService.list(queryWrapper);
        AppBookContent appBookContent = iAppBookContentService.getById(list.get(Integer.parseInt(params.get("index").toString())).getId());
        if (StringUtils.isEmpty(appBookContent.getContent())) {
            String url = "https://www.bookstack.cn" + appBookContent.getHref();
            System.out.println("**********************2 " + url);
            url = URLDecoder.decode(url, String.valueOf(StandardCharsets.UTF_8));
//            //模拟浏览器访问，防止阻止跳到登录页面
//            Connection mozilla = Jsoup.connect(url).userAgent("Mozilla");
//            Document document = mozilla.get();
            // 获取文档对象
            Document document = null;
            try {
                Connection con = Jsoup.connect(url).userAgent(
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
                        .timeout(30000); // 设置连接超时时间

                Connection.Response response = con.execute();

                if (response.statusCode() == 200) {
                    document = con.get();
                    Element element = document.body();
                    Element j_goodsList = element.getElementsByTag("article").get(0);
                    System.out.println(j_goodsList.toString());
                    appBookContent.setContent(j_goodsList.toString());
                    iAppBookContentService.updateById(appBookContent);
                } else {
                    System.out.println(response.statusCode());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.toString());
            }
        }
        list.clear();
        list.add(appBookContent);
        return PageUtils.buildDataInfo(list);
    }

    /**
     * 查询书籍内容
     */
    @ApiOperation("查询书籍内容列表")
    @GetMapping("/chaptersContentWithToken")
    public TableDataInfo<AppBookContent> chaptersContentWithToken(@RequestParam Map<String, Object> params) throws Exception {
        QueryWrapper<AppBookContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id,catalogue_name,seq,level,parent_id ");
        queryWrapper.eq("book_id", params.get("bookId").toString());
        queryWrapper.last("limit 1000");
        List<AppBookContent> list = iAppBookContentService.list(queryWrapper);
        AppBookContent appBookContent = iAppBookContentService.getById(list.get(Integer.parseInt(params.get("index").toString())).getId());
        if (StringUtils.isEmpty(appBookContent.getContent())) {
            String url = "https://www.bookstack.cn" + appBookContent.getHref();
            System.out.println("**********************2 " + url);
            url = URLDecoder.decode(url, String.valueOf(StandardCharsets.UTF_8));
//            //模拟浏览器访问，防止阻止跳到登录页面
//            Connection mozilla = Jsoup.connect(url).userAgent("Mozilla");
//            Document document = mozilla.get();
            // 获取文档对象
            Document document = null;
            try {
                Connection con = Jsoup.connect(url).userAgent(
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
                        .timeout(30000); // 设置连接超时时间

                Connection.Response response = con.execute();

                if (response.statusCode() == 200) {
                    document = con.get();
                    Element element = document.body();
                    Element j_goodsList = element.getElementsByTag("article").get(0);
                    System.out.println(j_goodsList.toString());
                    appBookContent.setContent(j_goodsList.toString());
                    iAppBookContentService.updateById(appBookContent);
                } else {
                    System.out.println(response.statusCode());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.toString());
            }
        }
        list.clear();
        list.add(appBookContent);
        //增加阅读记录
        AppInteractRecord appInteractRecord = new AppInteractRecord();
        appInteractRecord.setId(IDUtils.getId());
        appInteractRecord.setType("book");
        appInteractRecord.setCreateTime(new Date());
        appInteractRecord.setSourceId(appBookContent.getBookId());
        appInteractRecord.setInteractType("view");
        appInteractRecord.setUserId(SecurityUtils.getLoginUser().getAppUser().getId());
        iAppInteractRecordService.save(appInteractRecord);
        return PageUtils.buildDataInfo(list);
    }



    /**
     * 查询书籍内容app内跳转
     */
    @ApiOperation("查询书籍内容app内跳转")
    @GetMapping("/chaptersContentHref")
    public TableDataInfo<AppBookContent> chaptersContentHref(@RequestParam Map<String, Object> params) throws Exception {
        QueryWrapper<AppBookContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id,catalogue_name,seq,level,parent_id ");
        queryWrapper.eq("book_id", params.get("bookId").toString());
        queryWrapper.eq("href", params.get("href").toString());
        queryWrapper.last("limit 1");
        List<AppBookContent> list = iAppBookContentService.list(queryWrapper);
        AppBookContent appBookContent = list.get(0);
        if (StringUtils.isEmpty(appBookContent.getContent())) {
            String url = "https://www.bookstack.cn" + appBookContent.getHref();
            System.out.println("**********************2 " + url);
            url = URLDecoder.decode(url, String.valueOf(StandardCharsets.UTF_8));
//            //模拟浏览器访问，防止阻止跳到登录页面
//            Connection mozilla = Jsoup.connect(url).userAgent("Mozilla");
//            Document document = mozilla.get();
            // 获取文档对象
            Document document = null;
            try {
                Connection con = Jsoup.connect(url).userAgent(
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
                        .timeout(30000); // 设置连接超时时间

                Connection.Response response = con.execute();

                if (response.statusCode() == 200) {
                    document = con.get();
                    Element element = document.body();
                    Element j_goodsList = element.getElementsByTag("article").get(0);
                    System.out.println(j_goodsList.toString());
                    appBookContent.setContent(j_goodsList.toString());
                    iAppBookContentService.updateById(appBookContent);
                } else {
                    System.out.println(response.statusCode());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.toString());
            }
        }
        list.clear();
        list.add(appBookContent);
        return PageUtils.buildDataInfo(list);
    }


    /**
     * 导出书籍内容列表
     */
    @ApiOperation("导出书籍内容列表")
    @PreAuthorize("@ss.hasPermi('app:bookContent:export')")
    @Log(title = "书籍内容", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R<AppBookContentVo> export(@Validated AppBookContentBo bo, HttpServletResponse response) {
        List<AppBookContentVo> list = iAppBookContentService.queryList(bo);
        ExcelUtil<AppBookContentVo> util = new ExcelUtil<AppBookContentVo>(AppBookContentVo.class);
        return util.exportExcel(list, "书籍内容");
    }

    /**
     * 获取书籍内容详细信息
     */
    @ApiOperation("获取书籍内容详细信息")
    @PreAuthorize("@ss.hasPermi('app:bookContent:query')")
    @GetMapping("/{id}")
    public R<AppBookContentVo> getInfo(@ApiParam("主键")
                                       @NotNull(message = "主键不能为空")
                                       @PathVariable("id") Long id) {
        return R.success(iAppBookContentService.queryById(id));
    }

    /**
     * 新增书籍内容
     */
    @ApiOperation("新增书籍内容")
    @PreAuthorize("@ss.hasPermi('app:bookContent:add')")
    @Log(title = "书籍内容", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody AppBookContentBo bo) {
        return toAjax(iAppBookContentService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改书籍内容
     */
    @ApiOperation("修改书籍内容")
    @PreAuthorize("@ss.hasPermi('app:bookContent:edit')")
    @Log(title = "书籍内容", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody AppBookContentBo bo) {
        return toAjax(iAppBookContentService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除书籍内容
     */
    @ApiOperation("删除书籍内容")
    @PreAuthorize("@ss.hasPermi('app:bookContent:remove')")
    @Log(title = "书籍内容", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iAppBookContentService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }
}
